//
//  ComposeViewController.swift
//  weibo
//
//  Created by 叶子韬韬 on 2017/5/7.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

import UIKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    @IBOutlet weak var picView: PicPikerCollectionView!
    //toolbar
    @IBOutlet weak var picPickeViewBottomCanstant: NSLayoutConstraint!
    
    internal lazy var emotoVC:EmoticonViewController = EmoticonViewController {[weak self] (emoticon) in
        
        self?.textView.insertEmoticon(emoticon: emoticon)
        self?.textViewDidChange(self!.textView)
    }

    
    @IBAction func emoticonBtnClick(_ sender: Any) {
    
        //退出键盘
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView != nil ? nil : emotoVC.view
        
        //弹出键盘
        textView.becomeFirstResponder()
    }
    @IBOutlet weak var toolBarBottomCanstant: NSLayoutConstraint!

    @IBOutlet var textView: ComposeTextView!
    
    internal lazy var images:[UIImage] = [UIImage]()
    
    //监听事件的点击
    @IBAction func `internal`(_ sender: Any) {

        textView.resignFirstResponder()

    
        picPickeViewBottomCanstant.constant = UIScreen.main.bounds.height*0.65
        UIView.animate(withDuration: 0.5) { 
            self.view.layoutIfNeeded()
        }
        
    }

    internal lazy var titleView:ComposeTitleView = ComposeTitleView()
    override func viewDidLoad() {
        super.viewDidLoad()
        
      

        // Do any additional setup after loading the view.
        
        setupNavigationBar()
        
        //监听键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.keyboardWillChangeFrame(note:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.addPhoto), name: NSNotification.Name.init(rawValue: PicPikerAddPhoto), object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(ComposeViewController.removePhoto(note:)), name: NSNotification.Name.init(rawValue: PicPikerRemovePhoto), object: nil)
        
    }


    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }

}
// MARK:- #注释>设置UI
extension ComposeViewController{
    //设置左右item
    internal func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(ComposeViewController.closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .plain, target: self, action: #selector(ComposeViewController.sendItemClick))
        navigationItem.rightBarButtonItem?.isEnabled = false
        titleView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 40)
        navigationItem.titleView = titleView
    }
    
}
// MARK:- #注释>监听事件
extension ComposeViewController{
    internal func closeItemClick(){
        dismiss(animated: true, completion: nil)
    }
    internal func sendItemClick(){
        
        let stsuesText = textView.getEmoticonString()
        
        //获取用户选中的照片
        if let image = images.first {
            
            NetworkTools.shareInstance.sendStatus(statusText: stsuesText, image: image, isSuccess: { (isSuccess) in
                SVProgressHUD.showSuccess(withStatus: "发送微博成功")
                self.dismiss(animated: true, completion: nil)
            })
            
        }else{
            
            NetworkTools.shareInstance.sendStatus(statusText: stsuesText) { (isSuccess) in
                
                if isSuccess {
                    SVProgressHUD.showSuccess(withStatus: "发送微博成功")
                    self.dismiss(animated: true, completion: nil)
                }else{
                    SVProgressHUD.showError(withStatus: "发送微博失败")
                }
                
            }

        }
        
        
        
      
        
        
       
    }
    internal func keyboardWillChangeFrame(note:NSNotification){
//        print(note.userInfo ?? "saa")
        
        //获取动画执行时间
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! TimeInterval
        
        //获取监听的最终的y值
        let endFrame = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let y = endFrame.origin.y
        
        //计算工具类距离底部的间距
        let margn = UIScreen.main.bounds.height - y
        
        //执行动画
        toolBarBottomCanstant.constant = margn
        
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
        
    }
    
}
// MARK:- #注释>添加照片和删除照片的事件
extension ComposeViewController {
    
    internal func addPhoto(){
        
        //1.判断相册源是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            return
        }
        
        //2.创建照片选择控制器
        let ipc = UIImagePickerController()
        
        //3. 设置照片源
        ipc.sourceType = .photoLibrary
        
        //设置代理
        ipc.delegate = self
        // 弹出选择照片控制器
        present(ipc, animated: true, completion: nil)
    }
    
    internal func removePhoto(note:NSNotification){
    
        guard let image = note.object as? UIImage else{
            return
        }
        
        guard let index  = images.index(of: image) else {
            return
        }
        images.remove(at: index)
        
        picView.images = images
        
        
    }

}
extension ComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //选中的照片添加到数组中
        images.append(image)
        //展示数据
        self.picView.images = images
        
        //退出选中照片控制器
        picker.dismiss(animated: true, completion: nil)
    }
    
}
// MARK:- #注释>uitextview 代理
extension ComposeViewController :UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        
        self.textView.placHolderLabel.isHidden = textView.hasText
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
}
